import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/vehicle_details_entity.dart';
import 'package:nyh_motorcade_app/entity/vehicle_type_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/utils/verify_utils.dart';

class AddVehicleController extends GetxController {
  TextEditingController vehicleNumberController = TextEditingController();
  TextEditingController remarksController = TextEditingController();
  FocusNode vehicleNumberFocus = FocusNode();
  FocusNode remarksFocus = FocusNode();

  bool isOwnVehicle = true;
  String vehicleNumber = "";
  String motorcadeId = "";
  String motorcadeName = "";
  String vehicleType = "";
  String vehicleTypeName = "";
  bool isEnableState = true;
  bool isQuota = false;
  double quota = 0.0;
  String cycleType = "";
  String cycleName = "";
  String unitType = "";
  String unitName = "";
  String remarks = "";

  List<VehicleTypeEntity> vehicleTypeList = [];

  //编辑时参数
  VehicleDetailsEntity? entity;
  String vehicleId = "";

  //是否返回
  bool isReturn = false;

  @override
  void onReady() {
    super.onReady();
    initData();
  }

  void changeVehicleBelong() {
    isOwnVehicle = !isOwnVehicle;
    update();
  }

  void setVehicleNumber(String value) {
    vehicleNumber = value;
    update();
  }

  Future<void> goToSelectMotorcadePage() async {
    vehicleNumberFocus.unfocus();
    remarksFocus.unfocus();
    dynamic data = await Get.toNamed(Routes.selectMotorcade);
    if (data != null && data is Map) {
      motorcadeId = data[Constant.PARAM_MOTORCADE_ID];
      motorcadeName = data[Constant.PARAM_MOTORCADE_NAME];
      update();
    }
  }

  void changEnableState(bool value) {
    isEnableState = value;
    update();
  }

  void changQuotaState(bool value) {
    isQuota = value;
    if (!isQuota) {
      quota = 0.0;
      cycleType = "";
      cycleName = "";
      unitType = "";
      unitName = "";
    }
    update();
  }

  Future<void> goToQuotaPage() async {
    vehicleNumberFocus.unfocus();
    remarksFocus.unfocus();
    remarksFocus.unfocus();
    dynamic data = await Get.toNamed(Routes.quota, arguments: {
      Constant.PARAM_QUOTA: quota,
      Constant.PARAM_QUOTA_CYCLE_TYPE: cycleType,
      Constant.PARAM_QUOTA_CYCLE_NAME: cycleName,
      Constant.PARAM_QUOTA_UNIT_TYPE: unitType,
      Constant.PARAM_QUOTA_UNIT_NAME: unitName,
    });
    if (data != null && data is Map) {
      quota = data[Constant.PARAM_QUOTA];
      cycleType = data[Constant.PARAM_QUOTA_CYCLE_TYPE];
      cycleName = data[Constant.PARAM_QUOTA_CYCLE_NAME];
      unitType = data[Constant.PARAM_QUOTA_UNIT_TYPE];
      unitName = data[Constant.PARAM_QUOTA_UNIT_NAME];
      update();
    }
  }

  void setRemarks(String text) {
    remarks = text;
    update();
  }

  bool isComplete() {
    if ((isQuota && quota <= 0.0)) {
      return false;
    }
    return vehicleNumber.isNotEmpty && motorcadeId.isNotEmpty;
  }

  Future<void> onConfirm() async {
    if ((isQuota && quota <= 0.0)) {
      return;
    }
    if (vehicleNumber.isEmpty || motorcadeId.isEmpty) {
      return;
    }
    if (!VerifyUtils.isCarNumber(vehicleNumber)) {
      ToastUtils.toast("请输入正确的车牌号");
      return;
    }

    vehicleNumberFocus.unfocus();
    remarksFocus.unfocus();
    remarksFocus.unfocus();

    httpManager.post(
      Get.context,
      HttpAddress.ADD_OR_UPDATE_VEHICLE_INFO,
      vehicleId.isNotEmpty
          ? {
              "superId": await SPUtils.getString(SPUtils.COMPANY_ID),
              "id": vehicleId,
              "belongToType": isOwnVehicle ? Constant.OWN_VEHICLE : Constant.EXTERNAL_VEHICLE,
              "vehicleNumber": vehicleNumber,
              "motorcadeId": motorcadeId,
              "type": vehicleType.isNotEmpty ? vehicleType : null,
              "status": isEnableState ? 1 : 0,
              "quotaStatus": isQuota ? 1 : 0,
              "totalQuota": quota,
              "circle": cycleType.isNotEmpty ? cycleType : null,
              "unit": unitType.isNotEmpty ? unitType : null,
              "remake": remarks,
            }
          : {
              "superId": await SPUtils.getString(SPUtils.COMPANY_ID),
              "belongToType": isOwnVehicle ? Constant.OWN_VEHICLE : Constant.EXTERNAL_VEHICLE,
              "vehicleNumber": vehicleNumber,
              "motorcadeId": motorcadeId,
              "type": vehicleType,
              "status": isEnableState ? 1 : 0,
              "quotaStatus": isQuota ? 1 : 0,
              "totalQuota": quota,
              "circle": cycleType.isNotEmpty ? cycleType : null,
              "unit": unitType.isNotEmpty ? unitType : null,
              "remake": remarks,
            },
      isToast: true,
      isLoadingDialog: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          return;
        }
        if (isReturn) {
          Get.back(result: {});
        } else {
          Get.offNamed(Routes.vehicleDetails, arguments: data.toString());
        }
      },
    );
  }

  Future<List<VehicleTypeEntity>> getVehicleType() async {
    if (vehicleTypeList.isNotEmpty) {
      return vehicleTypeList;
    }
    HttpResult httpResult = await httpManager.post(Get.context, HttpAddress.GET_VEHICLE_TYPE, {}, isToast: true, isLoadingDialog: true);
    dynamic data = httpResult.data;
    if (data == null) {
      return [];
    }
    if (data is List) {
      vehicleTypeList = data.map((element) {
        return VehicleTypeEntity().fromJson((element as Map<String, dynamic>));
      }).toList();
      return vehicleTypeList;
    }
    return [];
  }

  void changeVehicleType(int index) {
    String type = vehicleTypeList[index].dictdataValue ?? "";
    String name = vehicleTypeList[index].dictdataName ?? "";
    if (vehicleType != type) {
      vehicleType = type;
      vehicleTypeName = name;
      update();
    }
  }

  void initData() {
    dynamic arguments = Get.arguments;
    if (arguments != null && arguments is Map) {
      dynamic data = arguments[Constant.PARAM_ENTITY];
      isReturn = arguments[Constant.PARAM_IS_RETURN] ?? false;
      if (data != null) {
        entity = data as VehicleDetailsEntity;
        vehicleId = entity!.id ?? "";
        String belongingType = (entity!.belongToType ?? "");
        isOwnVehicle = belongingType.isEmpty || belongingType == Constant.OWN_VEHICLE;
        vehicleNumber = entity!.vehicleNumber ?? "";
        vehicleNumberController.text = vehicleNumber;
        motorcadeId = entity!.motorcadeId ?? "";
        motorcadeName = entity!.motorcadeName ?? "";
        vehicleType = entity!.type ?? "";
        vehicleTypeName = entity!.typeName ?? "";
        isEnableState = entity!.status == 1;
        isQuota = (entity!.refuelQuota ?? 0.0) > 0.0;
        quota = entity!.refuelQuota ?? 0.0;
        cycleType = entity!.circle ?? "";
        cycleName = entity!.circleName ?? "";
        unitType = entity!.unit ?? "";
        unitName = entity!.unitName ?? "";
        remarks = entity!.remake ?? "";
        remarksController.text = remarks;
        update();
      }
    }
  }
}
